package mes.kanban.util;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Redis 实体类转换辅助类，
 * 
 * 有时候由于系列化 效率低占用内存大，因此可以用这个转成Json存储
 * 
 * 这是redis支持的类型String
 * 
 * 
 * @author gjy
 *
 * 2018年1月18日上午11:05:37
 */
public class JsonUtil implements Serializable{

	private static final long serialVersionUID = 5745318203492235323L;
	
	/**
	 * 实体类转成json
	 * @param pojo
	 * @return
	 * @throws JsonProcessingException
	 */
	public static String changeObjectToJson(Object pojo) throws JsonProcessingException {
		
		//转换器  
		ObjectMapper mapper = new ObjectMapper(); 
		
		String value = mapper.writeValueAsString(pojo);
		
		return value;
	}
	
	/**
	 * 集合类转成Json
	 * @param colls
	 * @return
	 * @throws JsonProcessingException
	 */
	@SuppressWarnings("rawtypes")
	public static String changeObjectToJson(Collection colls) throws JsonProcessingException {
		
		//转换器  
		ObjectMapper mapper = new ObjectMapper();
		
		String value = mapper.writeValueAsString(colls);
		
		return value;
	}
	
	/**
	 * json 转成map
	 * @param json
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static Map<?, ?> changeJsonToMap(String json) throws JsonParseException, JsonMappingException, IOException{
		
		//转换器  
		ObjectMapper mapper = new ObjectMapper();
		
		return mapper.readValue(json, Map.class);
		
	}
	
	
	/**
	 * 转换成指定类型
	 * @param json
	 * @param t
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T changeJsonToOther(String json,T t) throws JsonParseException, JsonMappingException, IOException {
		
		//转换器  
		ObjectMapper mapper = new ObjectMapper();
		
		return mapper.readValue(json, (Class<T>) t);
		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object changeJsonToPOJO(String json,Class clazz) throws JsonParseException, JsonMappingException, IOException {
		
		//转换器  
		ObjectMapper mapper = new ObjectMapper();
		
		return mapper.readValue(json, clazz);
	}
	

}
